
<div class="container-fluid">
    <div class="toolbar">
        <button class="btn btn-sm btn-success" id="add-bush-btn" data-toggle='modal' data-target='#modal-form' data-whatever='@mdo' data-type="add">添加</button>
    </div>

    <table id="table"></table>
</div>

<div class="modal fade" id="modal-form" tabindex="-1" role="dialog" aria-labelledby="form-title">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="form-title"></h4>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <label for="role-name"  class="control-label">角色名：</label>
                        <input type="text" class="form-control" id="role-name">
                    </div>
                    <div class="form-group">
                        <label for="role-code"  class="control-label">唯一编码：</label>
                        <input type="text" class="form-control" id="role-code">
                    </div>
                    <div class="form-group">
                        <label for="role-name"  class="control-label">菜单授权：</label>
                        <div id="menu-tree"></div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary"  data-dismiss="modal" id="submit">确定</button>
            </div>
        </div>
    </div>
</div>
<link rel="stylesheet" href="/static/plugins/js/boostrap-treeview/css/bootstrap-treeview.min.css">
<script src="/static/plugins/js/boostrap-treeview/js/bootstrap-treeview.min.js"></script>
<script>
    $(function () {

        let app={

            tableObj:$('#table'),
            modal:$('#modal-form'),
            roleNameObj:$('#role-name'),
            menuTreeObj:$('#menu-tree'),
            roleCodeObj:$('#role-code'),
            submitObj:$('#submit'),
            init:function (){
                let self=this;
                self.initTable();
                self.event();
            },
            initTable:function(){
                let self=this;
                self.tableObj.destroyTable().initTable({
                    url: '/admin/role/page',
                    uniqueId: "id",
                    columns: [
                        {
                            title: '角色名',
                            visible: true,
                            align: 'center',
                            field: 'name',
                            valign: 'middle',
                            width:"15%"

                        },
                        {
                            title: '唯一编码',
                            field: 'code',
                            visible: true,
                            align: 'center',
                            valign: 'middle',
                            sortable: false,
                            width:"15%"
                        },


                        {
                            title: '创建时间',
                            field: 'created_at',
                            visible: true,
                            align: 'center',
                            valign: 'middle',
                            sortable: false,
                            width:"15%"
                        },
                        {
                            title: '操作',
                            field: 'operator',
                            visible: true,
                            align: 'center',
                            valign: 'middle',
                            sortable: false,
                            width:"25%",
                            formatter: function (value, row, index) {
                                value=row["id"]
                                let url='/admin/role/menutree?role_id='+value+'&tag=${.tag}&ts=${.ts}'
                                return "<div class='btn-group operator-group' ><a  data-type='edit' class='btn btn-xs  btn-info'  data-toggle='modal' data-target='#modal-form' data-whatever='@mdo' data-id="+value+">编辑</a><a class='btn btn-xs  btn-danger remove-ele'  data-type='del'  data-toggle='modal'  data-id="+value+">删除</a></div>"
                            }
                        }
                    ]
                });
            },
            event:function(){
                let self=this;
               self.modal.on('show.bs.modal', function (event) {

                    let button = $(event.relatedTarget),
                        dType = button.data('type'),
                        modal = $(this),
                        roleNameObj=self.roleNameObj,
                        id=button.data('id'),
                        roleCodeObj=self.roleCodeObj;

                    $(this).attr("data-type",dType).attr("data-id",id);
                    if(!id){
                        id=0;
                    }
                    doGet("/admin/role/getrolemenutree?id="+id,function (data){

                       self.menuTreeObj.treeview({
                            data: data.data,
                            showIcon: true,
                            showCheckbox: true,
                            showBorder: true,
                            onNodeChecked: function(event, node) {
                                let selectNodes = getChildNodeIdArr(node); //获取所有子节点
                                if (selectNodes) { //子节点不为空，则选中所有子节点
                                    self.menuTreeObj.treeview('checkNode', [selectNodes, { silent: true }]);
                                }
                                setParentNodeCheck(node);
                            },
                            onNodeUnchecked: function (event, node) {
                                let selectNodes = getChildNodeIdArr(node); //获取所有子节点
                                if (selectNodes) { //子节点不为空，则取消选中所有子节点
                                    self.menuTreeObj.treeview('uncheckNode', [selectNodes, { silent: true }]);
                                }
                            }
                        });

                    })

                    switch (dType){
                        case 'info':
                            modal.find('.modal-title').text('查看')
                            //不可编辑
                            roleNameObj.attr("readonly",true)
                            doGet("/admin/role/find?id="+id,function(data){
                                roleNameObj.val(data.data.name);
                                roleCodeObj.val(data.data.code);
                            })
                            return
                        case 'edit':
                            modal.find('.modal-title').text('编辑')
                            doGet("/admin/role/find?id="+id,function(data){
                                roleNameObj.val(data.data.name);
                                roleCodeObj.val(data.data.code);
                            })
                            return
                    }

                }).on('hide.bs.modal', function (event) {
                    self.restModal();

                });
               self.tableObj.on('click','.remove-ele',function (){
                    let id=parseInt($(this).attr('data-id'))
                    doPost("/admin/role/remove",{id:id},function (data){
                        self.refreshTale();
                    });
                });
               self.submitObj.click(function (){
                    let modal=self.modal,
                        dType = modal.attr('data-type'),
                        id=parseInt(modal.attr('data-id')),
                        roleNameObj=self.roleNameObj,
                        nodes=self.menuTreeObj.treeview('getChecked'),
                        nodeIds=[],
                        roleCodeObj=self.roleCodeObj;

                    if(nodes){
                        nodes.forEach(function (node){
                            nodeIds.push(node.id,node.pid);
                        });
                    }



                    switch (dType){
                        case "add":

                            doPost("/admin/role/add",{
                                "name":roleNameObj.val(),
                                "code":roleCodeObj.val(),
                                "memo":"",
                                "menu_ids":nodeIds.join(",")
                            },function (){
                                refreshTale();
                            })

                            break;
                        case "edit":
                            doPost("/admin/role/update",{
                                "id":id,
                                "name":roleNameObj.val(),
                                "code":roleCodeObj.val(),
                                "memo":"",
                                "menu_ids":nodeIds.join(",")
                            },function (){
                                refreshTale();
                            })

                            break;

                    }




                });
            },
            restModal:function(){
                let self=this;
                self.roleNameObj.attr("readonly",false).val('')
            },
            refreshTale:function () {
               let self = this;
               self.initTable();
            }

        }

        app.init();


    });





    function getChildNodeIdArr(node) {
        let ts = [];
        if (node.nodes) {
            for (x in node.nodes) {
                ts.push(node.nodes[x].nodeId);
                if (node.nodes[x].nodes) {
                    var getNodeDieDai = getChildNodeIdArr(node.nodes[x]);
                    for (j in getNodeDieDai) {
                        ts.push(getNodeDieDai[j]);
                    }
                }
            }
        } else {
            ts.push(node.nodeId);
        }
        return ts;
    }

    function setParentNodeCheck(node,level) {
        let parentNode = $("#menu-tree").treeview("getNode", node.parentId);
        if (parentNode.nodes) {
            let checkedCount = 0;
            for (let x in parentNode.nodes) {
                if (parentNode.nodes[x].state.checked) {
                    checkedCount++;
                } else {
                    break;
                }
            }

            if (checkedCount >= parentNode.nodes.length) {
                $("#menu-tree").treeview("checkNode", parentNode.nodeId);
                setParentNodeCheck(parentNode,level++);
            }

        }
    }






</script>
